package com.example.demo.Controler;

import com.example.demo.Model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

@Controller
@ResponseBody//必须加的
public class TestDemo2 {
    //通过url来向后端传递参数
    @GetMapping("/get1")
    public String getParam1(String name){
        return "value->"+name;
    }
    /*
    通过url获取多个参数
     */
    @GetMapping("/get2")
    public String getPara2(String name,Integer num){
        return "name->"+name+"| num->"+num;
    }
    /*
    通过一个自己创建的对象来接受url传递的参数
     */
    @GetMapping("/get3")
    public String getParam3(Student stu){
        return "name = "+stu.getName()+" | id = "+stu.getId()+" | sex = "+stu.getSex();
    }

    /*
    后端接收json对象
     */
    @RequestMapping("/get4")
    //这里如果不加@RequestBody就会报404
    public HashMap<String,Object>  getParam4(@RequestBody Student stu){
        HashMap<String,Object> result=new HashMap<>();
        result.put("name",stu.getName());
        result.put("id",stu.getId());
        result.put("sex",stu.getSex());
        return result;
    }

    /*
    获取文件
     */
    @RequestMapping("/get5")
    public String getParam5(String name, @RequestPart("myfile") MultipartFile file) throws IOException {
        //获取文件后缀名
        //String fileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //文件保存地址
        //String filePath = ClassUtils.getDefaultClassLoader().getResource("static").getPath() + "/" + UUID.randomUUID() + fileName;
        file.transferTo(new File("/Users/mamba24/Desktop/boutique-code-gathering-place"));
        return "success";
    }

    /*
    获取cookie和session
     */
    @RequestMapping("/get6")
    public String getParam6(@CookieValue("krik") String str){
        return "cookie = "+str;
    }

}
